package com.kkb.kkbadmin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kkb.kkbadmin.dao.UserMapper;
import com.kkb.kkbadmin.domain.User;
import com.kkb.kkbadmin.domain.dto.UserDto;
import com.kkb.kkbadmin.domain.vo.FameBGListVO;

import com.kkb.kkbadmin.service.ProjectRegisterService;
import com.kkb.kkbadmin.service.UserRoleService;
import com.kkb.kkbadmin.service.UserService;
import com.kkb.kkbcommon.exception.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表 服务实现类
 *
 * @author 赵裕源
 * @since 2021-08-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private ProjectRegisterService projectRegisterService;

    /**
     * 带条件的分页查询
     *
     * @param condition 条件
     * @param pageNum   页码
     * @param pageSize  每页显示行数
     * @return pageInfo, PageHelper的分页类
     */
    @Override
    public PageInfo<FameBGListVO> findPage(Long roleId, UserDto condition, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Long> userIds = userRoleService.findUserIdListByRoleId(roleId);
        List<FameBGListVO> fameBGListVOS = this.selectByConditionAndUserIds(condition, userIds);
        return new PageInfo<>(fameBGListVOS);
    }

    /**
     * 根据用户Id列表List的条件返回用户列表List
     *
     * @param condition 包含用户名的搜索条件
     * @param userIds   用户Id列表
     * @return 用户列表List
     */
    @Override
    public List<FameBGListVO> selectByConditionAndUserIds(UserDto condition, List<Long> userIds) {

        if (CollUtil.isEmpty(userIds)) Asserts.fail("没有查询到相关用户");

        String name = condition.getName();
        List<User> users = this.lambdaQuery()
                .like(ObjectUtil.isNotNull(name), User::getName, name)
                .in(User::getId, userIds)
                .list();


        // 查找需要返回的用户信息放在vo中返回vo列表
        return users.stream().map(user -> {
            FameBGListVO vo = new FameBGListVO();
            Long id = user.getId();
            vo.setId(id);
            vo.setUrl(user.getHeadUrl());
            vo.setName(user.getName());
            vo.setJob(user.getJob());
            // 根据用户id查找已完成的项目数
            vo.setProjectNum(projectRegisterService.completedProjects(id));
            return vo;
        }).sorted((vo1, vo2) -> vo2.getProjectNum() - vo1.getProjectNum()).collect(Collectors.toList());
    }
}
